import {
  ArgumentsHost,
  ExceptionFilter,
  HttpException,
  NotFoundException,
  UnauthorizedException,
  UnprocessableEntityException
} from '@nestjs/common'

import { Response } from 'express'
interface IException {
  error: string
  message: string
}

export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse<Response>()

    let status = 500
    let message = '服务器内部错误'
    let code = -1
    let data = null

    if (exception instanceof HttpException) {
      status = exception.getStatus()
      const exceptionResponse = exception.getResponse() as string | IException
      console.log(
        exceptionResponse,
        'exceptionResponse HttpExceptionFilter handler'
      )

      if (typeof exceptionResponse === 'string') {
        message = exceptionResponse
      } else if (typeof exceptionResponse === 'object') {
        message = exceptionResponse.message
        data = exceptionResponse.error
      }
      code = status
      if (status !== 401) {
        status = 200
      }
    } else {
      message = '未知错误'
      data = 'Unknown error'
    }

    response.status(status).json({
      code,
      data,
      message
    })
  }
}
